/**
 *
 */
package com.dhcc.android.base.utils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;

import com.dhcc.android.base.common.adapter.ImageGridAdapter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


/**
 * 拍照处理类
 *
 * @author pengling
 * @date 2015-2-27
 */
public class PhotoUtil {
    private final int CAMERA_RESULT = 800;
    private Activity activity;
    public String filepath;


    public PhotoUtil(Activity activity) {
        this.activity = activity;
    }

    public void setFilePath(String filepath) {
        this.filepath = filepath;
    }

    public ImageGridAdapter imageGridAdapter;

	public void takePhoto(final String path, ImageGridAdapter imageGridAdapter,PhotoUtilListener photoUtilListener) {
        photoUtilListener.setClickSaveFalse();
		this.imageGridAdapter = imageGridAdapter;

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				intent.putExtra("aa", "222");
				mPhotoPath = path;
				File mPhotoFile = getFile();
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(mPhotoFile));
				activity.startActivityForResult(intent, CAMERA_RESULT);
			}
		}, "takePhoto");
		thread.start();

	}

    public interface PhotoUtilListener{
        void setClickSaveFalse();
    }

    public String mPhotoPath;
    public String oldPhotoPath;

    public File getFile() {
        oldPhotoPath = mPhotoPath;
        File mPhotoFile = new File(mPhotoPath);
        if (mPhotoFile.exists() || StringUtil.isEmpty(mPhotoPath)) {// 照片存在
            mPhotoPath = getSavePath(FileUtil.getPhotoFileName(".jpg"));
        }
        System.out.println("mPhotoPath:" + mPhotoPath);
        return FileUtil.createFile(mPhotoPath);
    }

    public String getSavePath(String name) {
        String path = filepath + "/" + name;
        return path;
    }

    /**
     * 重命名文件夹
     *
     * @param path    路径
     * @param newName 新名字
     * @return
     */
    public Boolean renameFile(String path, String newName) {
        File f = new File(path);
        String c = f.getParent();
        File newFile = new File(c + "/" + newName + ".jpg");
        mPhotoPath = c + "/" + newName + ".jpg";
        System.out.println("新文件夹地址：" + mPhotoPath);
        return f.renameTo(newFile);
    }

    /**
     * 获取文件大小
     *
     * @param path
     * @return
     */
    public long getPhotoSize(String path) {
        if (StringUtil.isNotEmpty(path)) {
            File f = new File(path);
            if (f.exists() && f.isFile()) {
                return f.length();
            }
        }
        return 0;
    }

    /**
     * 添加文字水印,不建议使用
     */
    @Deprecated
    public static Bitmap waterMark(Bitmap oldImg, String title) {
        if (oldImg == null) {
            System.out.println("########图片为空");
            return null;
        }
        // 获取原图片的尺寸
        int h = oldImg.getHeight();
        int w = oldImg.getWidth();

        // 创建一个和原图一样大小的新图片
        Bitmap nb = Bitmap.createBitmap(w, h, Config.ARGB_8888);

        Canvas cv = new Canvas(nb); // 画布
        cv.drawBitmap(nb, 0, 0, null); // 在0,0的位置开始画入原图

        Paint photoPaint = new Paint(); // 画笔
        photoPaint.setDither(true);
        photoPaint.setFilterBitmap(true);

        Rect src = new Rect(0, 0, w, h);// 创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, w, h);// 创建一个指定的新矩形的坐标
        cv.drawBitmap(oldImg, src, dst, photoPaint);// 将photo 缩放或则扩大到
        // dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.DEV_KERN_TEXT_FLAG);// 设置画笔
        textPaint.setTextSize(200.0f);// 字体大小
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);// 采用默认的宽度
        textPaint.setColor(Color.RED);// 采用的颜色

        cv.drawText(title, 20, h - 20, textPaint);

        cv.save(Canvas.ALL_SAVE_FLAG);
        cv.restore();

        System.out.println("########保存绘制成功");
        return nb;
    }

    public void dealPhoto(String file, String mark) {
        PhotoTask task = new PhotoTask(file, mark);
        task.start();
    }

    public Bitmap bitmap;

    public class PhotoTask extends Thread {
        private String file;

        private boolean isFinished;
        private String mark;

        public PhotoTask(String file, String mark) {
            this.file = file;
            this.mark = mark;
        }

        @Override
        public void run() {
            bitmap = doPhoto(file, mark);
        }
    }

    /**
     * 生成照片和添加水印，mark为水印文；用","隔开来换行
     *
     * @param file
     * @param mark
     * @return
     */
    public Bitmap doPhoto(String file, String mark) {
        BufferedOutputStream bos = null;
        Bitmap icon = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap ss = BitmapFactory.decodeFile(file, options); // 此时返回bm为空
            System.out.println("ss:" + ss);
            float percent = options.outHeight > options.outWidth ? options.outHeight / 960f
                    : options.outWidth / 960f;

            if (percent < 1) {
                percent = 1;
            }
            int width = (int) (options.outWidth / percent);
            int height = (int) (options.outHeight / percent);
            icon = Bitmap.createBitmap(width, height, Config.RGB_565);

            // 初始化画布 绘制的图像到icon上
            Canvas canvas = new Canvas(icon);
            // 建立画笔
            Paint photoPaint = new Paint();
            // 获取跟清晰的图像采样
            photoPaint.setDither(true);
            // 过滤一些
            options.inJustDecodeBounds = false;

            Bitmap prePhoto = BitmapFactory.decodeFile(file);
            System.out.println("@@@@@@@@@@@@" + prePhoto);
            if (percent > 1) {
                prePhoto = Bitmap.createScaledBitmap(prePhoto, width, height,
                        true);
            }
            canvas.drawBitmap(prePhoto, 0, 0, photoPaint);

            if (prePhoto != null && !prePhoto.isRecycled()) {
                prePhoto.recycle();
                prePhoto = null;
                System.gc();
            }

            if (StringUtil.isNotEmpty(mark)) {// 加水印文字
                // 设置画笔
                Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                        | Paint.DEV_KERN_TEXT_FLAG);
                // 字体大小
                textPaint.setTextSize(30.0f);
                // 采用默认的宽度
                textPaint.setTypeface(Typeface.DEFAULT);
                // 采用的颜色
                textPaint.setColor(Color.YELLOW);
                String[] mark_array = mark.split(",");// 逗号隔开来换行
                for (int i = mark_array.length - 1; i > -1; i--) {
                    String markstr = mark_array[i];
                    float textWidth = textPaint.measureText(markstr);
                    int j = (mark_array.length - i) * 35;
                    canvas.drawText(markstr, 10, height - j, textPaint);
                }
            }

            bos = new BufferedOutputStream(new FileOutputStream(file));

            int quaility = (int) (100 / percent > 80 ? 80 : 100 / percent);
            icon.compress(CompressFormat.JPEG, 100, bos);

            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return icon;
    }

    public int getRotate(String str) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(str);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    public Bitmap rotateBitmap(Bitmap bitmap, int angle) {

        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    public boolean rotateBitmap(String path, int angle) {
        boolean flag = false;

        Bitmap bitmap = pathToBitmap(path);
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        try {
            FileOutputStream fos = new FileOutputStream(new File(path));
            resizedBitmap.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        resizedBitmap.recycle();
        resizedBitmap = null;

        bitmap.recycle();
        bitmap = null;

        return flag;
    }


    public String getCurrTime(String pattern) {
        if (pattern == null) {
            pattern = "yyyyMMddHHmmss";
        }
        return (new SimpleDateFormat(pattern)).format(new Date());
    }

    public Bitmap pathToBitmap(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        // options.inJustDecodeBounds = true; // �Ȼ�ȡԭ��С
        Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);
        // options.inJustDecodeBounds = false; // ��ȡ�µĴ�С
        // int sampleSize = (int) (options.outHeight / (float) 200);
        // if (sampleSize <= 0)
        // sampleSize = 1;
        // options.inSampleSize = sampleSize;
        // scanBitmap = BitmapFactory.decodeFile(path, options);
        return scanBitmap;
    }

    public void releaseImage(String path) {
        if (mImageCache.containsKey(path)) {
            SoftReference<Bitmap> reference = mImageCache.get(path);
            Bitmap bitmap = reference.get();
            if (null != bitmap) {
                bitmap.recycle();
            }
            mImageCache.remove(path);
            System.out.println("删掉删掉");
        }

    }

    public void releaseImage() {
        mImageCache.clear();
    }

    private HashMap<String, SoftReference<Bitmap>> mImageCache = new HashMap<String, SoftReference<Bitmap>>();

    public Bitmap loadBitmapImage(String path) {
        Bitmap bitmap = null;
        try {
            if (mImageCache.containsKey(path)) {
                SoftReference<Bitmap> softReference = mImageCache.get(path);
                bitmap = softReference.get();
                if (null != bitmap)
                    return bitmap;
            }
            bitmap = BitmapFactory.decodeFile(path);
            mImageCache.put(path, new SoftReference<Bitmap>(bitmap));
        } catch (Exception e) {
            CommenUtil.toast("内存溢出", activity);
        } catch (OutOfMemoryError e) {
            CommenUtil.toast("内存溢出", activity);
        }

        return bitmap;
    }

    public boolean deleteAttachmentFile(String savePath) {
        System.out.println("delete:" + savePath);
        boolean flag = true;
        try {
            File file = new File(savePath);
            if (file != null) {
                if (file.exists()) {
                    flag = file.delete();
                }
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public int saveBitmap(String path, Bitmap bitmap) {
        System.out.println("sss" + path);
        int result = -1;
        try {
            FileOutputStream baos = new FileOutputStream(new File(path));
            // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            // File file=new File(path);
            // BufferedOutputStream baos = new BufferedOutputStream(new
            // FileOutputStream(file));

            Matrix matrix = new Matrix();
            matrix.postScale(0.3f, 0.3f); // 长和宽放大缩小的比例
            Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            // saveBitmap2file(bitmap, path);
            // bitmap = zoomImage(bitmap, bitmap.getWidth() / 3.5,
            // bitmap.getHeight() / 3.5);
            // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            resizeBmp.compress(CompressFormat.JPEG, 100, baos);
            baos.flush();
            baos.close();
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage   ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    public String url2Path(Uri url, Activity activity) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = activity.managedQuery(url, proj, null, null,
                null);
        int actual_image_column_index = actualimagecursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor
                .getString(actual_image_column_index);
        return img_path;
    }


    //=================================================================

    /**
     * 拍照
     * 开启一个线程
     */
    public void takePhoto(final String path) {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra("aa", "222");
                mPhotoPath = path;
                File mPhotoFile = getFile();
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                activity.startActivityForResult(intent, CAMERA_RESULT);
            }
        }, "takePhoto");
        thread.start();

    }


}
